# coding=utf-8
__author__ = 'liubin'

from flask import render_template, redirect, url_for, request
from flask.views import View
from flask.ext.restful import Resource
from flask.ext.login import login_user, logout_user, login_required, current_user
from flask.ext.babelex import gettext as _
from project import app, User, api_view, db
from project.forms import LoginForm, ChangePwdForm


class LoginView(View):
    """
    登录视图
    """
    methods = ['GET']

    def dispatch_request(self):
        """
        请求处理
        :return:
        """
        return render_template('login.html')

# url指定
app.add_url_rule('/login', view_func=LoginView.as_view('login'))


class LoginApi(Resource):
    """
    restful 用
    """

    def post(self, **kwargs):
        """
        指定POST方法
        :param kwargs:
        :return:
        """
        # 使用Form验证
        form = LoginForm(csrf_enabled=False)
        messages = []
        if form.validate_on_submit():
            # 验证成功
            user = User.query.filter_by(name=form.name.data, pwd=form.pwd.data).first()
            if user is not None:
                # 登录操作
                login_user(user, remember=form.remember.data)
                return {'success': True}
            else:
                # 使用国际化
                messages.append(_('Login failed'))
                # 返回错误信息
                return {'success': False, 'messages': messages}
        else:
            # 验证失败
            messages.append(_('Check failed'))
            print(form.errors)
            return {'success': False, 'messages': messages}

# 映射restful的url
api_view.add_resource(LoginApi, '/login', endpoint="login_post")


class LogoutView(View):
    """
    登出视图
    """
    methods = ['GET']

    def dispatch_request(self):
        logout_user()
        return redirect(url_for('index'))

# url指定
app.add_url_rule('/logout', view_func=LogoutView.as_view('logout'))


class ChangePwdView(View):
    """
    密码变更视图
    """
    methods = ['GET']
    decorators = [login_required]

    def dispatch_request(self):
        return render_template('change_pwd.html')


app.add_url_rule('/change_pwd', view_func=ChangePwdView.as_view('change_pwd'))


class ChangePwdApi(Resource):
    """
    resultful 用
    """
    method_decorators = [login_required]

    def post(self, **kwargs):
        """
        密码变更的POST
        :param kwargs:
        :return:
        """
        form = ChangePwdForm(csrf_enabled=False)
        messages = []
        if form.validate_on_submit():
            print('username', current_user.name)
            print(current_user.name, form.old_pwd.data)
            user = User.query.filter_by(name=current_user.name, pwd=form.old_pwd.data).first()
            if user is not None:
                user.pwd = form.new_pwd.data
                db.session.commit()
                return {'success': True}
            else:
                messages.append(_('Old password is wrong'))
                print('aaa', messages)
                return {'success': False, 'messages': messages}
        else:
            messages = form.errors.values()
            print('bbb', messages)
            return {'success': False, 'messages': messages}


api_view.add_resource(ChangePwdApi, '/change_pwd', endpoint="change_pwd_post")